from datetime import date, datetime
from enum import Enum
from joblib import delayed
from uuid import UUID


def safe_delayed(func):
    """包装器，捕获异常并返回 (结果, 错误信息)"""

    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs), None
        except Exception as e:
            return None, str(e)

    return delayed(wrapper)


def limit_iso_str_to_second_str(time_str: str):
    ts = int(datetime.fromisoformat(time_str).timestamp())
    return datetime.fromtimestamp(ts).isoformat()


escape_chars_map = {
    "\b": "\\b",
    "\f": "\\f",
    "\r": "\\r",
    "\n": "\\n",
    "\t": "\\t",
    "\0": "\\0",
    "\a": "\\a",
    "\v": "\\v",
    "\\": "\\\\",
    "'": "\\'",
}


def escape_param(item):
    if item is None:
        return "NULL"

    elif isinstance(item, datetime):
        return "'%s'" % item.strftime("%Y-%m-%d %H:%M:%S")

    elif isinstance(item, date):
        return "'%s'" % item.strftime("%Y-%m-%d")

    elif isinstance(item, str):
        return "'%s'" % "".join(escape_chars_map.get(c, c) for c in item)

    elif isinstance(item, list):
        return "[%s]" % ", ".join(str(escape_param(x)) for x in item)

    elif isinstance(item, (tuple, set)):
        return "(%s)" % ", ".join(str(escape_param(x)) for x in item)

    elif isinstance(item, Enum):
        return escape_param(item.value)

    elif isinstance(item, UUID):
        return "'%s'" % str(item)

    else:
        return item
